package cn.johnyu.base.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class SessionFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession();
        System.out.println(session);
        if(session==null){
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Unauthorized");
        }
        else{
            Object customer = request.getSession().getAttribute("customer");
            if (customer == null) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Unauthorized");
            }
            else{
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }
}
